import { UnwrapRef } from "vue";
import api from "@/utils";

export default function SubTableData(emit: {
  (
    e: "sub-data-format",
    columnName: string,
    cellValue: string,
    callback: (value: string) => void
  ): void;
}) {
  // 数据规整
  // 对于Object类型，不能直接用, 如果是any object, 使用 Record<string, unknown>作为其申明.
  const subDataFormat = (
    row: UnwrapRef<never>,
    column: UnwrapRef<Record<string, string>>,
    cellValue: UnwrapRef<string>
  ) => {
    emit("sub-data-format", column.property, cellValue, (value: string) => {
      cellValue = value;
    });
    // 正则表达式判断是否是日期, 日期格式为 2021-12-26T06:51:12.000+00:00,此前父组件emit事件处理后的结果为yyyy年MM月dd日，有汉字，不会符合这个规范
    const regDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}\+\d{2}:\d{2}$/;
    const isDate = regDate.test(cellValue);
    if (isDate) {
      const date = new Date(cellValue);
      return api.formatDate(date, "yyyy年MM月dd日");
    }
    return cellValue;
  };
  return {
    subDataFormat,
  };
}
